<template>
  <view class="login-container">
    <uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
    <button type="primary" class="btn-login" @click="getUserInfo">一键登录</button>
    <text class="tips">登录后尽享更多权益</text>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'

  export default {
    name: "my-login",
    data() {
      return {

      };
    },
    computed: {
      ...mapState('m_user', ['redirectInfo']),
    },
    methods: {
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
      getUserInfo() {
        uni.getUserProfile({
          desc: "你的授权信息",
          success: res => {
            if (res.errMsg === "getUserProfile:ok") {
              this.updateUserInfo(res.userInfo)

              // 获取Token
              this.getToken(res.userInfo)
            }
          },
          fail: () => {
            return uni.$showMsg("您取消了授权！")
          }
        })
      },
      async getToken(info) {
        const [err, succ] = await uni.login().catch(err => err)

        if (err || succ.errMsg !== "login:ok") return uni.$showMsg("登录失败！")

        const query = {
          code: succ.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }

        // 由于接口无法使用，此处使用假数据token
        // const {
        //   data: res
        // } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
        // if(res.meta.status !== 200) return uni.$showMsg("登录失败！")
        this.navigateBack() //放在拿到token之前，就不会展示用户信息页面，直接跳转回去
        // this.updateToken(res.message.token)
        this.updateToken('Q0j4TwGTfTLGcicxTnY1VRG0AW6DAl5pxu')
      },
      navigateBack() {
        if (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
          uni.switchTab({
            url: this.redirectInfo.from,
            complete: () => {
              this.updateRedirectInfo(null)
            }
          })
        }
      },
    }
  }
</script>

<style lang="scss">
  .login-container {
    height: 750rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #f8f8f8;
    position: relative;
    overflow: hidden;

    &::after {
      content: "";
      display: block;
      width: 100%;
      height: 40px;
      background-color: white;
      position: absolute;
      bottom: 0;
      left: 0;
      transform: translateY(50%);
      border-radius: 50%;
    }

    .btn-login {
      margin: 15px 0;
      width: 90%;
      border-radius: 100px;
      background-color: #c00000;
    }

    .tips {
      font-size: 12px;
      color: gray;
    }
  }
</style>
